<template>
  <div class="app-container">

    <el-form v-show="showSearch" ref="elForm" :inline="true" :model="queryParams" :rules="rules" size="medium"
             label-width="100px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="主题名" prop="topicName">
        <el-input v-model="queryParams.topicName" placeholder="请输入主题名" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="设备组名" prop="groupName">
        <el-input v-model="queryParams.groupName" placeholder="请输入设备组名" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号" :maxlength="11" clearable
                  :style="{width: '100%'}"></el-input>
      </el-form-item>


      <el-form-item label="通知方式" prop="notificationMethod">
        <el-select v-model="queryParams.notificationMethod" placeholder="请选择通知方式" clearable>
          <el-option
            v-for="dict in dict.type.notification_method"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item size="large">
        <el-button type="primary" size="mini" icon="el-icon-search" @click="submitForm">搜索</el-button>
        <el-button size="mini" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:alarmsetting:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:alarmsetting:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:alarmsetting:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:alarmsetting:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="settingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="组名" align="center" prop="groupName"/>
      <el-table-column label="主题名" align="center" prop="topicName"/>
      <el-table-column label="用户名" align="center" prop="userName"/>
      <el-table-column label="邮件" align="center" prop="email"/>
      <el-table-column label="手机号" align="center" prop="phonenumber"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="通知方式" align="center" prop="notificationMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.notification_method" :value="scope.row.notificationMethod"/>
        </template>
      </el-table-column>


      <!--      <el-table-column label="此群管理者id" width="110" align="center" prop="adminUserId"/>-->
      <!--      <el-table-column label="此群管理者" width="110" align="center" prop="adminUserName"/>-->
      <!--      <el-table-column label="创建者" align="center" prop="createBy"/>-->
      <!--      <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->

      <!--      </el-table-column>-->
      <!--      <el-table-column label="更新者" align="center" prop="updateBy"/>-->
      <!--      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">-->

      <!--      </el-table-column>-->

      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column
        fixed="right"
        label="操作" width="130" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            v-if="scope.row.adminUserId === getUserId() "
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:alarmsetting:edit']"
          >修改
          </el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:alarmsetting:edit']"
            v-has-role="['admin']"
          >修改
          </el-button>

          <el-button
            v-if="scope.row.adminUserId === getUserId()"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:alarmsetting:remove']"
          >删除
          </el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:alarmsetting:remove']"
            v-has-role="['admin']"
          >删除
          </el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="告警主题" prop="selectedTopicValue">
          <el-cascader placeholder="请选择告警的主题" :show-all-levels="false"
                       v-model="form.selectedTopicValue"
                       :options="optionsTopic"
                       clearable
                       @change="handleChange"></el-cascader>

        </el-form-item>
        <el-form-item label="告警联系人" prop="selectedUserValue">
          <el-cascader :filterable="true" :props="userProps"
                       placeholder="请选择告警通知人" :show-all-levels="false"
                       v-model="form.selectedUserValue"
                       :disabled="disabled"
                       :options="optionsUser" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="通知方式" prop="notificationMethod">
          <el-select v-model="form.notificationMethod" placeholder="请选择通知方式" clearable>
            <el-option
              v-for="dict in dict.type.notification_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAdd">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>

import {delSetting,addSetting, getTopic, getUser, settingList} from "@/api/iot/alarmsetting";
import store from "@/store";


export default {
  name: "Monitor",
  dicts: ['sys_normal_disable', 'notification_method'],

  data() {
    return {
      loading: true,
      userProps: {multiple: true},
      optionsTopic: [],
      optionsUser: [],
      disabled: true,


      rowIds: [],
      // 非单个禁用
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      settingList: [],
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        selectedTopicValue: [],
        selectedUserValue: [],
        status: undefined,
        notificationMethod: undefined,
        userIds: [],
        groupId: undefined,
        topicId: undefined,

      },
      formRules: {
        selectedTopicValue: [
          {required: true, message: "主题不能为空", trigger: "blur"}
        ],
        selectedUserValue: [
          {required: true, message: "通知用户不能为空", trigger: "blur"}
        ],
        notificationMethod: [
          {required: true, message: "通知方式不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "blur"}
        ],

      },

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        userName: '',
        topicName: undefined,
        groupName: undefined,
        email: undefined,
        phonenumber: undefined,
        notificationMethod: '',
      },
      rules: {
        userName: [],
        topicName: [],
        groupName: [],
        email: [{
          pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
          message: '邮箱号格式错误',
          trigger: 'blur'
        }],
        phonenumber: [{
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        notificationMethod: [],
      },
      notificationMethodOptions: [{
        "label": "手机号",
        "value": "1"
      }, {
        "label": "邮箱",
        "value": "2"
      }, {
        "label": "手机号和邮箱",
        "value": "3"
      }],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
    this.getTopic();
  },
  methods: {
    getUserId() {
      return store.state.user.id
    },
    getList() {
      this.loading = true;
      settingList(this.queryParams).then(response => {
        this.settingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });


    },
    handleSelectionChange(selection) {
      this.rowIds = selection.map(item => item.rowId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        selectedTopicValue: [],
        selectedUserValue: [],
        status: "0",
        notificationMethod: "1",
        userIds: [],
        groupId: undefined,
        topicId: undefined,

      };
      this.resetForm("form");
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加告警配置";
    },

    submitForm() {
      this.queryParams.pageNum = 1;

      this.$refs['elForm'].validate(valid => {
        if (!valid)
          return
        this.getList()

      })
    },
    submitFormAdd() {
      this.$refs['form'].validate(valid => {
        if (!valid)
          return
        this.form.groupId = this.form.selectedTopicValue[0];
        this.form.topicId = this.form.selectedTopicValue[1];
        this.form.userIds= []
        this.form.selectedUserValue.forEach(item => {
          this.form.userIds.push(parseInt(item[0]))
        });

        addSetting(this.form).then(res =>{
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.disabled = true;
          this.getList();
        })

      })
    },

    resetForm() {
      this.$refs['elForm'].resetFields()
    },

    getUser(topicId,groupId) {
      this.loading = true;
      getUser(topicId,groupId).then(response => {
        this.optionsUser = response.data
        this.loading = false;
      });
    },
    getTopic() {
      this.loading = true;
      getTopic().then(response => {
        this.optionsTopic = response.data
        this.loading = false;
      });
    },
    handleChange(value) {
      if (value.length > 0) {
        this.disabled = false;
        this.getUser(value[1],value[0]);
      } else {
        this.disabled = true;
      }


    },
    handleUpdate(row) {
    },
    handleDelete(row) {


      delSetting(row.rowId || this.rowIds).then(res =>{
        this.getList();
      })

    },
    handleExport() {
      this.download('iot/alarm/setting/export', {
        ...this.queryParams
      }, `setting_${new Date().getTime()}.xlsx`)
    }


  },
};
</script>

